<?php
namespace frontend\controllers;

use common\models\Apply;
use common\models\Open;
use common\models\OpenFront;
use common\models\ShortMessage;
use common\models\User;
use Yii;
use common\models\LoginForm;
use frontend\models\PasswordResetRequestForm;
use frontend\models\ResetPasswordForm;
use frontend\models\ResetPassForm;
use frontend\models\SignupForm;
use frontend\models\ContactForm;
use yii\base\InvalidParamException;
use yii\helpers\Url;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
/**
 * Site controller
 */
class SiteController extends Controller
{
    /**
     * @inheritdoc
     */

    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['logout', 'signup'],
                'rules' => [
                    [
                        'actions' => ['signup'],
                        'allow' => true,
                        'roles' => ['?'],
                    ],
                    [
                        'actions' => ['logout'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
                'height' => 50,
                'width' => 80,
                'minLength' => 4,
                'maxLength' => 4
            ],
        ];
    }

    public function actionLogin()
    {
        $this->layout='meno.php';
        if (!\Yii::$app->user->isGuest) {
            return $this->redirect(['grouth/index']);
        }
        $switch=OpenFront::find()->one();
        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) { //将post数组压入对象 验证通过则登录成功
//        if ($model->load(Yii::$app->request->post()) ) {
//           p(Yii::$app->request->post());
//           p($model);die;
            $url = Url::previous();   //提取暂存的之前url地址 用户登录成功后返回
            if(!empty($url)){
                return $this->goBack();
            }
            else return $this->redirect(['grouth/index']);
        } else {
//p($switch);die;
            if($switch->switch==1){
                return $this->render('login_back', [
                    'model' => $model,
                ]);
            }else{
                return $this->render('login', [
                    'model' => $model,
                ]);
            }

        }
    }

    /**
     * Logs out the current user.
     *
     * @return mixed
     */
    public function actionLogout()
    {
        Yii::$app->user->logout();
        //    return $this->goHome();

        return $this->redirect(['grouth/index']);
    }

    /**
     * Displays contact page.
     *
     * @return mixed
     */
    public function actionContact()
    {
        $model = new ContactForm();

        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            //  p($_POST['ContactForm']['email']);die;
            if ($model->sendEmail(Yii::$app->params['adminEmail'])) {
                // p(Yii::$app->request->post()->email);die;
                Yii::$app->session->setFlash('success', 'Thank you for contacting us. We will respond to you as soon as possible.');
            } else {
                Yii::$app->session->setFlash('error', 'There was an error sending email.');
            }
            return $this->refresh();
        } else {
            return $this->render('contact', [
                'model' => $model,
            ]);
        }
    }


    /**
     * Signs user up.
     *
     * @return mixed
     */
    public function actionSignup()
    {
        $model = new SignupForm();

        if(Yii::$app->request->post()){

            $mess=Yii::$app->request->post();
            // p($mess);die;// 由于是采用登录 注册统一界面 所以数组 $mess['LoginForm']
            $mess['LoginForm']['username']='用户'.date('md',time()).rand(10,99);//重写username  随机用户名
            $content=$mess['duanxin'];
            $tel=$mess['LoginForm']['tel'];

            $result=ShortMessage::find()->where(['tel'=>$tel])->orderBy('id DESC')->one();//查询这个手机的验证码是否正确

            $model->username= $mess['LoginForm']['username']; //将数组压入注册对象
            $model->tel=  $mess['LoginForm']['tel'];
            $model->password= $mess['LoginForm']['password'];

            if(!empty($mess['invite'])){     //消耗邀请码,前端只使用了客户端验证，这一步为客户端正常验证的情况下生效
                $apply=Apply::find()->where(['res1'=>$mess['invite'],'tel'=>$model->tel])->one();
                if(!empty($apply)){
                    $apply->status=0;
                    $apply->res2="used";
                    $apply->save();
                }
            }

            if(!empty($result)&&$result->content==$content&&$model->validate()){
                if ($user = $model->signup()) {                //验证成功后注册账户
                    if (Yii::$app->getUser()->login($user)) {  //注册成功后直接登录
                        return $this->redirect(['usermess/update_a']);//a表示先补充第一项资料
                    }
                }
            }
            else  {
                return $this->redirect(['grouth/index']);
            }


        }

        return $this->render('signup', [
            'model' => $model,
        ]);
    }

    public function actionRequestPasswordReset()
    {
        $model = new PasswordResetRequestForm();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->sendEmail()) {
                Yii::$app->session->setFlash('success', 'Check your email for further instructions.');

                return $this->redirect(['grouth/index']);
            } else {
                Yii::$app->session->setFlash('error', 'Sorry, we are unable to reset password for email provided.');
            }
        }

        return $this->render('requestPasswordResetToken', [
            'model' => $model,
        ]);
    }

    public  function actionSend(){

        $mail= Yii::$app->mailer->compose();
        $mail->setTo('57827289@qq.com');
        $mail->setSubject("邮件测试");
//$mail->setTextBody('zheshisha ');   //发布纯文字文本
        $mail->setHtmlBody("<br>问我我我我我");    //发布可以带html标签的文本
        if($mail->send())
            echo "success";
        else
            echo "failse";
        die();
    }

    /**
     * Resets password.
     *
     * @param string $token
     * @return mixed
     * @throws BadRequestHttpException
     */
    public function actionResetPassword($token)
    {
        try {
            $model = new ResetPasswordForm($token);
        } catch (InvalidParamException $e) {
            throw new BadRequestHttpException($e->getMessage());
        }

        if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->resetPassword()) {
            Yii::$app->session->setFlash('success', 'New password was saved.');

            return $this->redirect(['grouth/index']);
        }

        return $this->render('resetPassword', [
            'model' => $model,
        ]);
    }
    public function actionLunbo(){
        $this->render('lunbo');
    }
    public function actionShortMess($tel){

        $num=mt_rand(1000,9999);


        $text="【Growthmemo】您的验证码是".$num."。如非本人操作，请忽略本短信";

        $result=ShortMessage::find()->where(['tel'=>$tel])->orderBy('id DESC')->one(); //查看时间间隔是否超过60s

        if(!empty($result)) $time_space=time()-strtotime($result->created_at);
        else $time_space=60;

        if(($time_space>=60))    Yii::$app->smser->send($tel, $text);   //若时间间隔大于60s 发送短信

        $shortMess=new ShortMessage();
        $shortMess->created_at=time();
        $shortMess->updated_at=time();
        $shortMess->tel=$tel;
        $shortMess->content=$num;
        if(($time_space>=60)&&$shortMess->validate()&&$shortMess->save()){  //插入新获得的验证码纪录
            echo "yes";
        }
        else echo "no";              //获取验证码失败
    }
    public function actionTelContent($tel,$content){

        $result=ShortMessage::find()->where(['tel'=>$tel])->orderBy('id DESC')->one();
        if(isset($result)&&$result->content==$content){

            return json_encode(1);  //最新一条内容吻合
        }
        else return json_encode(0); //其他情况
    }
    public function actionTelValidate($tel){ //判断电话号码是否存在  未加格式验证--

        $result=User::find()->where(['tel'=>$tel])->one();
        if(!empty($result)){
            return json_encode(1);  //最新一条内容吻合
        }
        else return json_encode(0); //其他情况
    }
    public  function actionReset(){
        //   p(1);die;

        $model=new ResetPassForm();

        //     p($model);die;
        if(Yii::$app->request->post()&&$model->load(Yii::$app->request->post()) && $model->validate()){
            $user=User::find()->where(['tel'=>$model->tel])->one();
            $pass=$model->password;
            if($model->load(Yii::$app->request->post()) && $model->validate()){}
            $user->password_hash=Yii::$app->security->generatePasswordHash($pass);
            $user->auth_key=Yii::$app->security->generateRandomString();
            $user->save();
            Yii::$app->session->setFlash('success', 'New password was saved.');
            return $this->redirect(['grouth/index']);
        }

        return $this->render('reset', [
            'model'=>$model
        ]);

    }
    public  function actionInvite($code,$tel){

        $apply=Apply::find()->where(['res1'=>$code,'tel'=>$tel,'status'=>1])->one();
        if(!empty($apply)){
            echo "yes";
        }else echo "no";
    }

}



